package cn.itcast.consumer.controller;

import cn.itcast.consumer.dimain.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    RestTemplate restTemplate;

    @Autowired
    DiscoveryClient discoveryClient;

    @GetMapping("/add/{id}")
    public Goods add(@PathVariable("id") int goodsId) {
        //远程调用
//        String url="http://127.0.0.1:8000/goods/findById/"+goodsId;
        //获取服务方队列
        List<ServiceInstance> instances = discoveryClient.getInstances("nacos-cn.itcast.provider");
        if (instances == null) {
            return null;
        }
        //取一个服务
        ServiceInstance serviceInstance = instances.get(0);
        //直接获取uri
        URI uri = serviceInstance.getUri();
        System.out.println(uri);
        String url = uri + "/goods/findById/" + goodsId;
        //restTemplate远程访问的一种模板
        ResponseEntity<Goods> forEntity = restTemplate.getForEntity(url, Goods.class);
        Goods goods = forEntity.getBody();
        return goods;
    }
}
